package controller;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import modal.UserModal;
import dao.UsersDAO;

/**
 * Servlet implementation class LoginController
 */
@WebServlet("/Default")
public class LoginController extends HttpServlet {
	private static final long serialVersionUID = 1L;

    /**
     * Default constructor. 
     */
	public LoginController() {

    }


	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doProcess(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doProcess(request, response);
	}

	private void doProcess(HttpServletRequest request,
			HttpServletResponse response) {
		try {
			UsersDAO udao= new UsersDAO();
			String email;
			String pass; 
			UserModal user; 
            HttpSession session = request.getSession();
            
            if (session.getAttribute("user")==null){
                email = request.getParameter("email").toString();
                pass = request.getParameter("pass").toString();
            }else {
                user=(UserModal) session.getAttribute("user");
                email = user.getEmail();
                pass = user.getPass();
            }
            UserModal us =udao.getUserwithEmail(email);
            udao.disconnnect();
            
            if(us.getPass().equals(pass)){
            	session.setAttribute("user", us);
            	session.setAttribute("deneme", "a");
            	request.getRequestDispatcher("/HomeController").forward(request, response);
            	
            } else {
            	//TODO set a warning saying wrong credentials and send back to login 
            	request.getRequestDispatcher("/login.jsp").forward(request, response);

            }         
            
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
